from douban.list_thread import timer
from douban.detail_thread import detail
from douban.mongo import db


class douban:
    def __init__(self, tags):
        self.tag = tags

    def run(self):
        li = []
        threadnum = 5
        pagesize = 5
        pageno = 0

        time1 = timer(self.tag, pageno * pagesize, pagesize)
        time1.start()
        time1.join()
        if time1.get_data():
            li.extend(time1.get_data())

        self.result = []

        index = 0
        while index < len(li) / threadnum + 1:
            innindex = 0
            threadnums = []
            while innindex < threadnum:
                if index * threadnum + innindex < len(li):
                    d1 = detail(li[index * threadnum + innindex]['url'])
                    d1.start()
                    threadnums.append(d1)
                    innindex += 1
                else:
                    break

            for item in threadnums:
                item.join()
                if item.get_detail():
                    self.result.append(item.get_detail())

            threadnums.clear()
            innindex = 0
            index += 1
        return self.result

    def insert_db(self, data):
        client = db().getClient()
        douban = client.douban
        movie = douban.movie
        for item in data:
            count = movie.find({"title":item['title']}).count()
            print(count)
            if count == 0:
                movie.insert(item)
